﻿Imports SilverMemory.Engine
Imports System.Xml.Linq

Public Class XmlCardFactory
  Implements ICardsFactory

  Private xmlUri As Uri
  Private cardsList As New List(Of Card)
  Public Event CardsReady(ByVal sender As Object, ByVal e As System.EventArgs) Implements Engine.ICardsFactory.CardsReady

  Public Function CreateUniqueCards() As System.Collections.Generic.IList(Of Engine.Card) Implements Engine.ICardsFactory.GetUniqueCards
    Return Me.cardsList
  End Function

  ''' <summary>
  ''' do request for the card urls in the cardConfiguration parameter
  ''' </summary>
  Public Sub Configure(ByVal params As System.Collections.Generic.IDictionary(Of String, String)) Implements Engine.ICardsFactory.Configure
    If Not params.ContainsKey("cardConfiguration") Then
      Throw New ArgumentException("cardConfiguration should point to the Xml file where the card urls can be found")
    End If
    Me.xmlUri = New Uri(params("cardConfiguration"))

    Dim request As New WebClient()
    AddHandler request.DownloadStringCompleted, AddressOf request_Completed
    request.DownloadStringAsync(xmlUri)
  End Sub

  ''' <summary>
  ''' parse the xml input document
  ''' </summary>
  Private Sub request_Completed(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
    Select Case True
      Case e.Cancelled
        'cancelled, do nothing
      Case e.Error IsNot Nothing
        Throw e.Error
      Case String.IsNullOrEmpty(e.Result)
        Throw New ArgumentException("No xml results from uri " & Me.xmlUri.OriginalString)
      Case Else
        'parse the document
        Dim configDoc = XDocument.Parse(e.Result)

        'get the urls
        Dim urls = From card In configDoc.<cards>.<card> Select card.@url

        'create the cards
        For Each url As String In urls
          Me.cardsList.Add(New Card(url))
        Next

        'publish to interested parties
        RaiseEvent CardsReady(Me, New EventArgs)
    End Select

  End Sub

End Class
